/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.cnguifang.feigewallet.ui;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.cnguifang.feigewallet.DemoApplication;
import com.cnguifang.feigewallet.DemoHelper;
import com.cnguifang.feigewallet.R;
import com.cnguifang.feigewallet.data.UserInfo;
import com.cnguifang.feigewallet.data.result.UserInfoResult;
import com.cnguifang.feigewallet.db.DemoDBManager;
import com.cnguifang.feigewallet.network.AppNetworkUtils;
import com.cnguifang.feigewallet.network.NetworkResultUtils;
import com.cnguifang.feigewallet.utils.QiniuUtils;
import com.cnguifang.feigewallet.utils.UserInfoUtils;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.mathum.baseapp.callback.UpLoadImgCallback;
import com.mathum.baseapp.data.BaseDialogData;
import com.mathum.baseapp.network.NetworkCallback;
import com.mathum.baseapp.network.NetworkUtils;
import com.mathum.baseapp.widget.RecyclerViewDialog;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.com.mathum.gallerylib.BastiGallery;

/**
 * Login screen
 */
public class UserInfoActivity extends BaseActivity {
    private static final String TAG = "UserInfoActivity";
    public static final int REQUEST_CODE_SETNICK = 1;
    private EditText usernameEditText;
    private EditText passwordEditText;

    private boolean progressShow;
    private boolean autoLogin = false;
    private TextView forgetPwd;
    private ImageView photo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // enter the main activity if already logged in
        if (DemoHelper.getInstance().isLoggedIn()) {
            autoLogin = true;
            startActivity(new Intent(UserInfoActivity.this, MainActivity.class));

            return;
        }
        setContentView(R.layout.em_activity_info);

        usernameEditText = (EditText) findViewById(R.id.username);
        passwordEditText = (EditText) findViewById(R.id.password);
        photo = findViewById(R.id.photo);
        forgetPwd = (TextView) findViewById(R.id.tv_forget);

        photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showSelectPhotoDialog();
            }
        });


        if (DemoHelper.getInstance().getCurrentUsernName() != null) {
            usernameEditText.setText(DemoHelper.getInstance().getCurrentUsernName());
        }

        TextView serviceCheckTV = (TextView) findViewById(R.id.txt_service_ckeck);
        serviceCheckTV.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);


    }


    /**
     * 弹出选择照片的对话框
     */
    private void showSelectPhotoDialog() {
        List<BaseDialogData> baseDataList = new ArrayList<>();
        baseDataList.add(new BaseDialogData("相机", 0));
        baseDataList.add(new BaseDialogData("图片", 1));
        RecyclerViewDialog recyclerViewDialog = RecyclerViewDialog.getInstance(baseDataList);
        recyclerViewDialog.show(getSupportFragmentManager(), "");
        recyclerViewDialog.setOnItemClickListener((position1, view1) -> {
            if (position1 >= 0 && position1 < baseDataList.size()) {
                BaseDialogData baseDialogData = baseDataList.get(position1);
                switch (baseDialogData.getId()) {
                    case 0:
                        BastiGallery.openCamera(UserInfoActivity.this, baseDialogData.getId());
                        break;
                    case 1:
                        BastiGallery.openGallery(this, baseDialogData.getId());
                        break;
                }
                recyclerViewDialog.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            //相机
            String url = BastiGallery.getmCurrentPhotoPath();
            String fileName = BastiGallery.getPathFromCamera(data, url);
            byte[] img = BastiGallery.Bitmap2Bytes(BastiGallery.getimage(fileName));
            upLoadFeedBackImg(img);
        } else if (requestCode == 1) {
            String fileName = BastiGallery.getPathFromGallery(this, data);
            if (TextUtils.isEmpty(fileName)) {
                Toast.makeText(UserInfoActivity.this, "相册异常", Toast.LENGTH_LONG).show();
                return;
            }
            byte[] img = BastiGallery.Bitmap2Bytes(BastiGallery.getimage(fileName));
            upLoadFeedBackImg(img);
        }
    }


    private void upLoadFeedBackImg(byte[] img) {
        progressShow = true;
        final ProgressDialog pd = new ProgressDialog(UserInfoActivity.this);
        pd.setCanceledOnTouchOutside(false);
        pd.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                Log.d(TAG, "EMClient.getInstance().onCancel");
                progressShow = false;
            }
        });
        pd.setMessage("正在上传");
        pd.show();
        QiniuUtils.getUploadManagerInstance();
        //已经上传过的不上传
        QiniuUtils.uploadImg(this, img, QiniuUtils.createImageKey(UserInfoUtils.getPhone(this)), new UpLoadImgCallback() {
            @Override
            public void onSuccess(String imgUrl) {
                pd.dismiss();
                Log.e("111111111111", "imgUrl = " + imgUrl);
                Glide.with(UserInfoActivity.this).load(imgUrl).into(photo);
            }

            @Override
            public void onFailure() {
                pd.dismiss();
            }
        });
    }

    /**
     * login
     *
     * @param view
     */
    public void login(View view) {
        if (!EaseCommonUtils.isNetWorkConnected(this)) {
            Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
            return;
        }
        String currentUsername = usernameEditText.getText().toString().trim();

        if (TextUtils.isEmpty(currentUsername)) {
            Toast.makeText(this, R.string.User_name_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }

        progressShow = true;
        final ProgressDialog pd = new ProgressDialog(UserInfoActivity.this);
        pd.setCanceledOnTouchOutside(false);
        pd.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                Log.d(TAG, "EMClient.getInstance().onCancel");
                progressShow = false;
            }
        });
        pd.setMessage("正在上传");
        pd.show();

    }

    /**
     * register
     *
     * @param view
     */
    public void register(View view) {
        startActivityForResult(new Intent(this, RegisterActivity.class), 0);
    }

    /**
     * SDK service check
     *
     * @param v
     */
    public void serviceCheck(View v) {
        startActivity(new Intent(this, ServiceCheckActivity.class));
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (autoLogin) {
            return;
        }
    }


    @Override
    public void onBackPressed() {
        Toast.makeText(this, "请先上传个人资料", Toast.LENGTH_LONG).show();
    }
}
